package com.sheep.spring;

import com.sheep.StringUtils;

import java.io.Closeable;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 默认工厂类
 *
 * @author wangze
 * @date 2020/07/15
 **/
public class DefaultBeanFactory implements BeanFactory, BeanDefinitionRegistery, Closeable {

    private Map<String, BeanDefinition> bdMap = new ConcurrentHashMap<>();
    private Map<String, Object> beanMap = new ConcurrentHashMap<>();

    @Override
    public void register(BeanDefinition bd, String beanName) {
        // Assert.assertNotNull("beanName不能为空 beanName", beanName);
        if (!bdMap.containsKey(beanName)) {
            bdMap.put(beanName, bd);
        }
    }

    @Override
    public BeanDefinition getBeanDefinition(String beanName) {
        if (bdMap.containsKey(beanName)) {
            return bdMap.get(beanName);
        }
        return null;
    }

    @Override
    public boolean containsBeanDefinition(String beanName) {
        return bdMap.containsKey(beanName);
    }

    @Override
    public Object getBean(String beanName) {
        if (beanMap.containsKey(beanName)) {
            return beanMap.get(beanName);
        }
        return null;

    }

    /**
     * 生成bean
     *
     * @return
     */
    public Object doGetBean(String beanName) {
        Object instance = this.beanMap.get(beanName);
        if (null != instance) {
            return instance;
        }
        //不存在，创建
        BeanDefinition beanDefinition = this.bdMap.get(beanName);
        //获取类型
        Class<?> beanClass = beanDefinition.getBeanClass();

        // 通过构造函数
        if (beanClass != null&&null==instance) {
            // 通过构造函数
            instance = this.createBeanByContruct(beanClass);
        }
        if(null == instance&&StringUtils.isNotBlank(beanDefinition.getBeanFactory())){
            //通过工厂创建
            instance = this.createBeanByFactoryMethod(beanDefinition);
        }
        // 通过静态方法创建
        if (null == instance && StringUtils.isNotBlank(beanDefinition.getStaticCreateBeanMethod())) {
            instance = this.createBeanByStaticFactoryMethod(beanDefinition);
        }

        this.doInit(beanDefinition, instance);
        //因为是新创建的，所以添加到map中,
        // 这里判断是否是单例模式，如果是单例，直接不添加到map中
        if(instance != null && beanDefinition.isSingleton()){
            beanMap.put(beanName, instance);
        }


        return instance;
    }

    /**
     * 生成bean之后，要做哪些初始化
     *
     * @param bd
     * @param instance
     */
    private void doInit(BeanDefinition bd, Object instance) {
        Class<?> beanClass = instance.getClass();
        if (StringUtils.isNotBlank(bd.getBeanInitMethod())) {
            try {
                // 利用反射，调用init方法
                Method method = beanClass.getMethod(bd.getBeanInitMethod(), null);
                method.invoke(instance, null);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 根据构造方法创造bean
     *
     * @param beanClass
     * @return
     */
    private Object createBeanByContruct(Class<?> beanClass) {
        Object obj = null;
        try {
            obj = beanClass.newInstance();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return obj;
    }

    /**
     * 普通工厂方法创建
     *
     * @param bd
     * @return
     */
    private Object createBeanByFactoryMethod(BeanDefinition bd) {
        Object instance = null;
        Object factory = this.doGetBean(bd.getBeanFactory());
        try {
            Method method = factory.getClass().getMethod(bd.getCreateBeanMethond(), null);
            instance = method.invoke(factory, null);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return instance;
    }

    /**
     * 静态方法创建实例
     *
     * @param bd
     * @return
     */
    private Object createBeanByStaticFactoryMethod(BeanDefinition bd) {
        Object instance = null;
        Class<?> beanClass = bd.getBeanClass();
        try {
            Method method = beanClass.getMethod(bd.getStaticCreateBeanMethod());
            instance = method.invoke(beanClass, null);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return instance;
    }

    /**
     * 实现destoryMethod方法
     */
    @Override
    public void close() {
        Set<Map.Entry<String, BeanDefinition>> entries = bdMap.entrySet();
        for (Map.Entry<String, BeanDefinition> entry : entries) {
            String beanDestoryMethod = entry.getValue().getBeanDestoryMethod();
            try {
                Method method = entry.getValue().getClass().getMethod(beanDestoryMethod);
                method.invoke(method, null);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
